package main

import (
	"encoding/json"
	"fmt"
	"github.com/robfig/cron"
	"log"
	model3 "order_srv/model"
	MQ "smart-health-platforms/inits"
	"smart-health-platforms/pkg"
)

/*
	func GetGoodsStatus(goodsId, skuId int) int {
		key := fmt.Sprintf("goods_stock:%d:%d", goodsId, skuId)
		stock, err := config.Rdb.LLen(config.Ctx, key).Result()
		if err != nil {
			log.Println("获取商品库存失败", err)
			return 0
		}
		return int(stock)
	}

// 返还库存

	func IncrActivityNum(goodsId int, skuId int) {
		key := fmt.Sprintf("goods_stock:%d:%d", goodsId, skuId)
		config.Rdb.LPush(config.Ctx, key, 1)

}
*/
func main() {
	rabbitmq := MQ.NewRabbitMQSimple("" +
		"2301a")
	simple, _ := rabbitmq.ConsumeSimple()
	forever := make(chan bool)
	//启用协程处理消息
	go func() {
		for d := range simple {
			var ConSumOrder model3.Order
			_ = json.Unmarshal(d.Body, &ConSumOrder)

			err := ConSumOrder.CreateOrder()
			if err != nil {
				pkg.Warn("创建订单失败")
				return
			}
			log.Println("订单创建成功", ConSumOrder)
			pkg.Info("订单创建成功")
			SyncGoodStock(int(ConSumOrder.Id))
		}
	}()
	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}

func SyncGoodStock(orderId int) { //同步商品库存定时任务
	c := cron.New()
	spec := "0 */15 * * * *"
	err := c.AddFunc(spec, func() {
		var orders model3.Order
		err := orders.GetByOrderId(orderId)
		if err != nil {
			pkg.Warn("获取订单信息失败")
			return
		}
		if orders.PayStatus == 1 {
			err = orders.DeleteOrder()
			if err != nil {
				pkg.Warn("删除订单失败")
				return
			}
		}
		log.Println("删除订单成功")
	})
	fmt.Println(err)
	c.Start()
	select {}
}
